package http.method.support;

import http.util.ReflectionUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;
import org.springframework.util.NumberUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.WebRequest;

import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class RequestParamMapMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return true;
    }

    /**
     * 简单初始化
     * @param req
     * @param parameter
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(FullHttpRequest req, MethodParameter parameter) throws Exception {
        Class<?> paramType = parameter.getParameterType();
        String parameterName = parameter.getParameterName();

        Map<String, Object> reqParam=parameter.getReqParam();
        Object arg= reqParam.get(parameterName);

        if(ReflectionUtil.isNumberType(paramType)){
            arg=ReflectionUtil.converToNumberType(arg,  (Class<Number>)paramType);
        }else if(arg == null && paramType == String.class && reqParam.get(HandlerMethodArgumentResolver.JSON) != null){
            Annotation[] parameterAnnotations = parameter.getParameterAnnotations();
            for (Annotation annotation : parameterAnnotations){
                if(annotation instanceof RequestBody){
                    arg=reqParam.get(HandlerMethodArgumentResolver.JSON);
                }
            }
        }
        if(arg == null && FullHttpRequest.class.isAssignableFrom(paramType)){
            arg=req;
        }
        if(arg == null){
            arg=paramType.newInstance();
            parameter.setWrapperBean(true);
        }
        return arg;
    }

}
